<template>
  <div class="academic-container">
    <div class="database-dashboard">
      <!-- 返回按钮 -->
      <div class="return-button">
        <el-button
          type="primary"
          @click="goBack"
          icon="el-icon-arrow-left"
          class="return-btn"
        >
          返回
        </el-button>
      </div>
      <!-- 数据库标题 -->
      <div class="academic-header">
        <div class="title-wrapper">
          <i class="el-icon-notebook-2"></i>
          <h1 class="academic-title">{{ dbname }}</h1>
        </div>
        <div class="decorative-line"></div>
      </div>
      <!-- 属性集合 -->
      <el-card class="academic-card" shadow="never">
        <div slot="header" class="academic-card-header">
          <span class="card-title-icon">◼</span>
          <span class="card-title-text">属性集U(Attributes Set)</span>
        </div>
        <div class="academic-tag-group">
          <div
            v-for="(attr, index) in atData"
            :key="index"
            class="academic-tag"
          >
            {{ attr.attributename }}
          </div>
        </div>
      </el-card>
      <!-- 函数依赖 -->
      <el-card class="academic-card" shadow="never">
        <div slot="header" class="academic-card-header">
          <span class="card-title-icon">◼</span>
          <span class="card-title-text">函数依赖集F(Functional Dependencies)</span>
        </div>
        <div class="dependency-group">
          <div
            v-for="(fd, index) in fdData"
            :key="index"
            class="dependency-item"
          >
            <div class="dependency-lhs">{{ formatAttributes(fd.lhs) }}</div>
            <div class="dependency-arrow">→</div>
            <div class="dependency-rhs">{{ formatAttributes(fd.rhs) }}</div>
          </div>
        </div>
      </el-card>

      <!-- 动态表格 -->
      <el-card class="academic-card" shadow="never">
        <div slot="header" class="academic-card-header">
          <span class="card-title-icon">◼</span>
          <span class="card-title-text">BCNF数据库不一致实例(Database Instance Data)</span>
        </div>
        <el-table
          :data="dynamicData"
          style="width: 100%"
          border
        >
          <el-table-column
            v-for="(column, index) in dynamicColumns"
            :key="index"
            :prop="column.name"
            :label="column.name"
          />
        </el-table>
      </el-card>
      <!-- 子集 -->
      <el-card class="academic-card" shadow="never">
        <div slot="header" class="academic-card-header">
          <span class="card-title-icon">◼</span>
          <span class="card-title-text">BCNF数据库一致子实例(Subset Database Instance Data)</span>
        </div>
        <el-table
          :data="setdynamicData"
          style="width: 100%"
          border
        >
          <el-table-column
            v-for="(column, index) in setdynamicColumns"
            :key="index"
            :prop="column.name"
            :label="column.name"
          />
        </el-table>
      </el-card>
      <el-card class="academic-card result-card" shadow="never">
        <div slot="header" class="academic-card-header">
         
          <span class="card-title-icon">◼</span>
          <span class="card-title-text">结果展示</span>
        </div>
        <div class="result-content">
          <!-- 最终结果展示 -->
          <div class="final-result-section">
            <el-card
              class="academic-card result-card"
              shadow="never"
              style="font-size: 18px; font-weight: bold; padding: 20px;"
            >
              <div v-if="result">
                <i class="el-icon-success" style="color: #67C23A; font-size: 24px;"></i>
                <span style="color: #67C23A; margin-left: 10px;">修复检查通过</span>
              </div>
              <div v-else>
                <i class="el-icon-error" style="color: #F56C6C; font-size: 24px;"></i>
                <span style="color: #F56C6C; margin-left: 10px;">修复检查未通过</span>
              </div>
            </el-card>
          </div>

          <!-- 一致性检查结果 -->
          <div class="consistency-section">
            <el-card
              v-if="resultData"
              class="academic-card result-card"
              shadow="never"
            >
              <div slot="header" class="academic-card-header">
                <span class="card-title-icon">◼</span>
                <span class="card-title-text">一致性检查结果 (Consistency Verification)</span>
              </div>
              <div class="result-content">
                <div class="verdict">
                  <i :class="resultIcon" :style="{ color: resultColor }"></i>
                  <span :style="{ color: resultColor }">{{ resultText }}</span>
                </div>
                <div class="log-section">
                  <h3>检查日志 Execution Logs:</h3>
                  <pre class="log-content">{{ processedLogs }}</pre>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 子集检查结果 -->
          <div class="subset-section">
            <el-card class="academic-card result-card" shadow="never">
              <div slot="header" class="academic-card-header">
                <span class="card-title-icon">◼</span>
                <span class="card-title-text">子集检查结果 (Subset Verification)</span>
              </div>
              <div class="result-content">
                <div class="verdict">
                  <i :class="subresultIcon" :style="{ color: subresultColor }"></i>
                  <span :style="{ color: subresultColor }">{{ subresultText }}</span>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 修复检查结果 -->
          <div class="repair-section">
            <el-card class="academic-card result-card" shadow="never">
              <div slot="header" class="academic-card-header">
                <span class="card-title-icon">◼</span>
                <span class="card-title-text">修复检查 (Repair Checking Result)</span>
              </div>
              <div class="result-content">
                <div class="verdict">
                  <i :class="repairIcon" :style="{ color: repairColor }"></i>
                  <span :style="{ color: repairColor }">{{ repairText }}</span>
                </div>
                <div v-if="repair_result !== null">
                  <div class="repair-details">
                    <div class="constant-c">常数 c（仅依赖于函数依赖集F）: {{ constant_c }}</div>
                    <div class="algorithm-description">
                      <h3>基于BCNF的数据库修复检查算法：</h3>
                      <ul>
                        <li>输入：两个BCNF实例R和R′，其中R′⊂R，R不满足F，而 R′ 满足F。</li>
                        <li>输出：判断R′是否为R的修复结果。</li>
                        <li>过程：</li>
                        <ul>
                          <li>测试是否存在一个元组集合 A*，满足以下条件：</li>
                          <ul>
                            <li>A* 非空。</li>
                            <li>∣A*∣ ≤ c。</li>
                            <li>A* 包含在R- R′ 中。</li>
                            <li>R′ ∪ A* 满足F。</li>
                          </ul>
                          <li>如果找到这样的集合 A*，则报告“R′ 不是 R 的修复结果”。</li>
                          <li>如果没有找到这样的集合 A*，则报告“R′ 是 R 的修复结果”。</li>
                        </ul>
                      </ul>
                    </div>
                  </div>
                  <div v-if="aStarTable.length > 0" class="a-star-table">
                    <h4>已找到的 A*</h4>
                    <el-table
                      :data="aStarTable"
                      style="width: 100%"
                      border
                      stripe
                      :header-cell-style="{ background: '#f8fafc', color: '#2c3e50', fontWeight: 'bold' }"
                    >
                      <el-table-column
                        v-for="column in aStarColumns"
                        :key="column.prop"
                        :prop="column.prop"
                        :label="column.label"
                        :width="column.width || ''"
                      ></el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { subconsistency_check } from "@/api/consistency";
import { checking_result } from "@/api/results";
import { subset_checking, repair_checking } from "@/api/rp";
import { setdbdetails, setshowinstance ,setdbshowinstance} from '@/api/db';

export default {
  name: "AcademicDBList",
  created() {
    this.read();
    this.showInstanceData();
  },
  computed: {
    ...mapGetters(["token", "setid"]),
    resultIcon() {
      return this.resultData?.consistent ? "el-icon-success" : "el-icon-error";
    },
    resultColor() {
      return this.resultData?.consistent ? "#67C23A" : "#F56C6C";
    },
    resultText() {
      return this.resultData?.consistent
        ? "数据库满足函数依赖集 (Consistency Verified)"
        : "存在不一致性冲突 (Consistency Violation Detected)";
    },
    subresultIcon() {
      return this.sub_result ? "el-icon-success" : "el-icon-error";
    },
    subresultColor() {
      return this.sub_result ? "#67C23A" : "#F56C6C";
    },
    subresultText() {
      return this.sub_result ? "通过" : "未通过";
    },
    repairIcon() {
      return this.repair_result ? "el-icon-success" : "el-icon-error";
    },
    repairColor() {
      return this.repair_result ? "#67C23A" : "#F56C6C";
    },
    repairText() {
      return this.repair_result ? "修复检查通过" : "修复检查未通过";
    },
    processedLogs() {
      return this.resultData?.logs?.join("\n") || "暂无日志信息";
    },
    aStarTable() {
      const parsedData = [];
      if (this.a_star.length > 0) {
        this.a_star.forEach((stmt) => {
          if (stmt.startsWith("INSERT INTO")) {
            const insertRegex = /INSERT INTO \w+ \((.+?)\) VALUES \((.+?)\)/i;
            const match = stmt.match(insertRegex);
            if (match) {
              const columnsPart = match[1];
              const valuesPart = match[2];
              const columns = columnsPart.split(/,\s*/).map(col => col.trim().toLowerCase());
              const rawValues = valuesPart.split(/,\s*(?=(?:[^']*'[^']*')*[^']*$)/);
              const values = rawValues.map(v => {
                let val = v.trim();
                if (val.startsWith("'") && val.endsWith("'")) {
                  val = val.slice(1, -1);
                }
                return val === 'NULL' ? null : val;
              });
              const rowData = {};
              columns.forEach((col, index) => {
                rowData[col] = values[index] || null;
              });
              parsedData.push(rowData);
            }
          }
        });
      }
      return parsedData;
    },
    aStarColumns() {
      if (this.aStarTable.length === 0) return [];
      const firstRow = this.aStarTable[0];
      return Object.keys(firstRow).map(key => ({
        prop: key,
        label: key.toUpperCase(),
        width: 120
      }));
    }
  },
  data() {
    return {
      dbData: [],
      keyword: "",
      resultData: null,
      sub_result: null,
      repair_result: null,
      check_result: [],
      constant_c: '',
      a_star: [],
      result: null,  // 初始化为 null，表示未完成验证
      dbname: '',
      fdData: [],
      atData: [],
      dynamicColumns: [],
      dynamicData: [],
      setdynamicColumns: [],
      setdynamicData: [],
    };
  },
  methods: {
    read() {
      this.result = null; // 重置 result 状态
      subconsistency_check(this.setid)
        .then((response) => {
          this.resultData = response.data.result;
          return subset_checking(this.setid);
        })
        .then((response) => {
          this.sub_result = response.data.sub_result;
          return repair_checking(this.setid);
        })
        .then((response) => {
          this.repair_result = response.data.check_result;
          this.constant_c = response.data.constant_c;
          this.a_star = response.data.a_star || [];
          this.updateFinalResult(); // 更新最终结果
          checking_result(this.result,this.setid)
        })
        .catch((error) => {
          console.error("检查过程中发生错误：", error);
          this.result = false; // 如果发生错误，验证失败
        });

        setdbdetails(this.setid).then(response => {
        this.dbname = response.data.dbname;
        this.atData = response.data.at;
        this.fdData = response.data.fd;
      }).catch(error => {
        console.error(error);
        this.$message.error('Database information retrieval failed');
      });

    },
    formatAttributes(str) {
      return str.split(',').join(', ');
    },
    updateFinalResult() {
      // 根据检查结果更新最终结果
      this.result = this.resultData?.consistent && this.sub_result && this.repair_result;
     
    },
    goBack() {
      this.$router.push('/RESULTS/allresults');
    },
    showInstanceData() {
      setshowinstance(this.setid).then(response => {
        const entity = response.data.entity;
        this.dynamicColumns = entity.columns.map(col => ({
          name: col.name,
          type: col.type
        }));
        this.dynamicData = entity.data;
      }).catch(error => {
        console.error(error);
        this.$message.error('Database instance data retrieval failed');
      });
      setdbshowinstance(this.setid).then(response => {
        const entity = response.data.entity;
        this.setdynamicColumns = entity.columns.map(col => ({
          name: col.name,
          type: col.type
        }));
        this.setdynamicData = entity.data;
      }).catch(error => {
        console.error(error);
        this.$message.error('Database instance data retrieval failed');
      });
    },
  },
  watch: {
    // 监控 resultData、sub_result 和 repair_result 的变化，动态更新 result
    resultData: { handler: 'updateFinalResult', deep: true },
    sub_result: 'updateFinalResult',
    repair_result: 'updateFinalResult'
  }
};
</script>

<style lang="scss" scoped>
.academic-container {
  padding: 40px 30px;
  background: #f8f9fa;
  min-height: 100vh;
  font-family: 'Helvetica Neue', Arial, sans-serif;

  .database-dashboard {
    max-width: 1000px;
    margin: 0 auto;
    position: relative;
  }

  .return-button {
    position: absolute;
    right: 20px;
    z-index: 10;
  }

  .academic-header {
    margin-bottom: 40px;
    padding: 0 20px;

    .title-wrapper {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .el-icon-notebook-2 {
        font-size: 36px;
        color: #2c3e50;
        margin-right: 16px;
      }

      .academic-title {
        margin: 0;
        font-size: 28px;
        color: #2c3e50;
        font-weight: 600;
        letter-spacing: 0.5px;
      }
    }

    .decorative-line {
      height: 2px;
      background: linear-gradient(90deg, #3498db 0%, rgba(52, 152, 219, 0.2) 100%);
    }
  }

  .academic-card {
    margin-bottom: 30px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background: #ffffff;

    ::v-deep .el-card__header {
      padding: 20px 24px;
      background: #f8fafc;
      border-bottom: 1px solid #e0e0e0;
    }

    .academic-card-header {
      display: flex;
      align-items: center;

      .card-title-icon {
        color: #3498db;
        margin-right: 12px;
        font-size: 18px;
      }

      .card-title-text {
        font-size: 18px;
        color: #2c3e50;
        font-weight: 500;
        letter-spacing: 0.3px;
      }
    }

    ::v-deep .el-card__body {
      padding: 24px;
    }

    &.result-card {
      margin-top: 20px;
      border-color: #e0e0e0;
      
      .result-content {
        .verdict {
          display: flex;
          align-items: center;
          margin-bottom: 20px;
          padding: 15px;
          background: #f8fafc;
          border-radius: 4px;

          i {
            font-size: 24px;
            margin-right: 12px;
          }

          span {
            font-size: 16px;
            font-weight: 500;
          }
        }

        .log-section {
          h3 {
            color: #606266;
            margin-bottom: 12px;
            font-size: 14px;
          }

          .log-content {
            padding: 15px;
            background: #f8fafc;
            border-radius: 4px;
            max-height: 300px;
            overflow: auto;
            font-family: Consolas, monospace;
            font-size: 13px;
            line-height: 1.6;
            color: #2c3e50;
            border: 1px solid #e0e0e0;

            &::-webkit-scrollbar {
              width: 6px;
            }

            &::-webkit-scrollbar-thumb {
              background: #c0c4cc;
              border-radius: 4px;
            }
          }
        }
      }
    }
  }

  .consistency-section {
    text-align: center;
    margin-top: 30px;

    .consistency-btn {
      padding: 12px 28px;
      font-size: 16px;
      letter-spacing: 0.5px;
      background: #3498db;
      border-color: #3498db;
      transition: all 0.3s;

      &:hover {
        background: #2980b9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
      }

      i {
        margin-right: 8px;
      }
    }
  }

  .academic-tag-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;

    .academic-tag {
      padding: 8px 18px;
      background: #f0f4f8;
      border: 1px solid #d0d7de;
      border-radius: 4px;
      color: #2c3e50;
      font-size: 14px;
      font-family: 'Courier New', monospace;
      letter-spacing: 0.5px;
      transition: all 0.2s;

      &:hover {
        background: #e3f2fd;
        border-color: #3498db;
      }
    }
  }

  .dependency-group {
    display: grid;
    gap: 16px;

    .dependency-item {
      display: flex;
      align-items: center;
      padding: 16px;
      background: #f8fafc;
      border: 1px solid #e0e0e0;
      border-radius: 4px;

      .dependency-lhs,
      .dependency-rhs {
        padding: 8px 16px;
        background: #ffffff;
        border: 1px solid #d0d7de;
        border-radius: 4px;
        font-family: 'Courier New', monospace;
        font-size: 15px;
        color: #2c3e50;
      }

      .dependency-arrow {
        margin: 0 16px;
        font-size: 20px;
        color: #3498db;
        font-weight: 500;
      }
    }
  }
}
</style>